<template>
  <div class="main">
    <div class="setting-container">
      <div class="setting-text">基本设置</div>
      <el-row>
        <el-col :span="24">
          <el-card :body-style="{ padding: '0px' }">
            <!-- 用户头像上传 -->
            <div class="setting-image">
              <el-upload
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
                :action="actionUrl"
                class="avatar-uploader images">
                <img v-if="avatarUrl" :src="avatarUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
            </div>
            <!-- 基本设置表单 -->
            <el-form ref="form" :model="form" :rules="formRules" label-width="120px" style="margin:5% 16%;width:60%;min-width:300px">
              <el-form-item label="姓名" prop="username">
                <el-col>
                  <el-input v-model="form.username" placeholder="请修改你的姓名"/>
                </el-col>
              </el-form-item>
              <el-form-item label="性别" prop="sex" style="margin-top:40px">
                <el-radio-group v-model="form.sex">
                  <el-radio label="男" class="radio"/>
                  <el-radio label="女" class="radio"/>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="学历" style="margin-top:40px">
                <el-radio-group v-model="form.education">
                  <el-radio label="高中" class="radio"/>
                  <el-radio label="大专" class="radio"/>
                  <el-radio label="本科" class="radio"/>
                  <el-radio label="研究生" class="radio"/>
                  <el-radio label="博士" class="radio"/>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="职位" prop="position" style="margin-top:40px">
                <el-col>
                  <el-input v-model="form.position" placeholder="请修改你的职位" style="width: 100%;"/>
                </el-col>
              </el-form-item>
              <el-form-item label="手机号" prop="phoneNumber" style="margin-top:40px">
                <el-col>
                  <el-input v-model="form.phoneNumber" placeholder="请修改你的手机号" style="width: 100%;"/>
                </el-col>
              </el-form-item>
              <el-form-item label="电子邮件" prop="email" style="margin-top:40px">
                <el-col>
                  <el-input v-model="form.email" placeholder="请修改你的电子邮件" style="width: 100%;"/>
                </el-col>
              </el-form-item>
              <el-form-item label="出生日期" prop="birth" style="margin-top:40px">
                <el-col>
                  <el-date-picker v-model="form.birth" type="date" placeholder="请选择你的出生年月日" style="width: 100%;" />
                </el-col>
              </el-form-item>
              <!-- <el-form-item label="入职时间" prop="entryDate" style="margin-top:40px">
                <el-col :span="11">
                  <el-date-picker v-model="form.entryDate" type="date" placeholder="选择日期" style="width: 100%;" />
                </el-col>
              </el-form-item> -->
              <el-form-item label="修改地址" prop="address" style="margin-top:40px">
                <el-input v-model="form.address" type="textarea" placeholder="请输入修改后的地址" />
              </el-form-item>
              <el-form-item style="margin-top:40px">
                <el-button :loading="editLoading" type="primary" @click.native.prevent="onSubmit">保存</el-button>
                <el-button @click="onCancel">取消</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { isvalidatePhoneNumber, isvalidateEmail } from '@/utils/validate'
import { getToken } from '@/utils/auth'
import { getUserMessage } from '@/api/home'
import { editUser } from '@/api/user'
import store from '@/store'
import util from '@/common/js/util'
export default {
  inject: ['reload'],
  name: 'Setting',
  data() {
    // 手机号
    const validatePhoneNumber = (rule, value, callback) => {
      if (!isvalidatePhoneNumber(value)) {
        callback(new Error('手机号总共要十一位且第一位必须以1开头，且第二位是3、4、5、7、8中的任意一个'))
      } else if (value === '') {
        callback(new Error('请输入你的手机号'))
      } else {
        callback()
      }
    }
    // 电子邮箱
    const validateEmail = (rule, value, callback) => {
      if (!isvalidateEmail(value)) {
        callback(new Error('邮箱域名只能是以163.com、qq.com、42du.cn结尾'))
      } else if (value === '') {
        callback(new Error('请输入你的电子邮箱'))
      } else {
        callback()
      }
    }
    // 性别
    const validateSex = (rule, value, callback) => {
      if (validateSex === '') {
        callback(new Error('请选择你的性别'))
      } else {
        callback()
      }
    }
    return {
      // 上传头像
      dialogVisible: false,
      actionUrl: '',
      baseUrl: '',
      form: {
        username: '',
        sex: '',
        birth: null,
        address: '',
        email: '',
        phoneNumber: '',
        education: '',
        position: ''
      },
      editLoading: false,
      url: '',
      formRules: {
        username: [{ required: true, message: '请输入你要修改的用户名', trigger: 'blur' }],
        position: [{ required: true, message: '请输入你要修改的职位', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择你的性别', trigger: 'blur', validator: validateSex }],
        birth: [{ type: 'date', required: true, message: '请选择你的出生日期', trigger: 'change' }],
        // entryDate: [{ type: 'string', required: true, message: '请选择你的入职时间', trigger: 'change' }],
        address: [{ required: true, message: '请输入你要修改的地址', trigger: 'blur' }],
        phoneNumber: [{ required: true, trigger: 'blur', validator: validatePhoneNumber }],
        email: [{ required: true, trigger: 'blur', validator: validateEmail }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'username',
      'age',
      'sex',
      'birth',
      'education',
      'position',
      'phoneNumber',
      'email',
      'password',
      'address',
      'entryDate',
      'avatarUrl'
    ]),
    headers() {
      return {
        token: getToken()
      }
    }
  },
  // 监听数据然后将string转为date
  watch: {
    form() {
      if (typeof this.form.birth === 'string') {
        this.form.birth = new Date(this.form.birth)
      }
    }
  },
  mounted() {
    this.getMessage()
    this.baseUrl = process.env.API_BASEURL
    this.actionUrl = process.env.API_BASEURL + '/upload'
  },
  methods: {
    getMessage() {
      getUserMessage().then((res) => {
        this.form = res.data
        this.editLoading = false
      })
    },
    handleAvatarSuccess(res, file) {
      store.dispatch('GetInfo').then(res => this.avatarUrl)
    },
    // 设置可上传图片大小及类型
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG && !isPNG) {
        this.$message.error('Avatar picture must be JPG or PNG format!')
      }
      if (!isLt2M) {
        this.$message.error('Avatar picture size can not exceed 2MB!')
      }
      console.log('图片认证成功')
      return (isJPG || isPNG) && isLt2M
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('确认保存吗？', '提示', {}).then(() => {
            this.editLoading = true
            const para = Object.assign({}, this.form)
            para.birth = (!para.birth || para.birth === '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd')
            editUser(para).then((res) => {
              this.editLoading = false
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.$refs['form'].resetFields()
              this.getMessage()
            })
          })
        }
      })
    },
    onCancel() {
      this.$router.push({ path: this.redirect || '/' })
    }
  }
}
</script>

<style scoped lang="scss">
.main {
 width: 100%;
 height: 100%;
 background-color: white;
 margin: -2% 0
}
.setting {
  &-container {
    margin: 2% 5%;
    width: 90%;
    box-sizing: border-box;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
    padding-top: 20px
  }
  &-image {
    width: 100%;
    margin-top: 50px
  }
  &-button{
    margin: 0 auto;
    display: flex;
    align-items: center;
    margin-top: 20px
  }
}
.el-row{
  margin-top: 20px
}
.bottom {
  margin-top: 13px;
  line-height: 12px;
}
.button_span{
  margin: 0 auto
}
.images {
  margin: 0 auto;
  vertical-align: middle;
  text-align: center;
}
.avatar-uploader, .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.avatar-uploader, .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  margin: 0 auto;
  vertical-align: middle;
  text-align: center;
  z-index: 99999;
}
</style>
